package com.zygh.lz.service.impl;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zygh.lz.dao.*;
import com.zygh.lz.entity.*;
import com.zygh.lz.entity.remould.Illegals;
import com.zygh.lz.util.DataTime;
import com.zygh.lz.util.DistanceUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;

@Service
public class IllegalDataService {

    @Resource
    private IllegalDataMapper illegalDataMapper;
    @Resource
    private IllegalMapper illegalMapper;
    @Resource
    private StaffMapper staffMapper;
    @Resource
    private SectionMapper sectionMapper;
    @Resource
    private InformationUserMapper informationUserMapper;
    @Resource
    private IllegalDeptMapper illegalDeptMapper;
    @Resource
    private PoliceDataMapper policeDataMapper;


    /**
     * 查询所有记录
     *
     * @return 返回集合，没有返回空List
     */
    public List<IllegalData> listAll() {
        return illegalDataMapper.listAll();
    }


    /**
     * 根据主键查询
     *
     * @param id 主键
     * @return 返回记录，没有返回null
     */
    public IllegalData getById(Integer id) {
        return illegalDataMapper.getById(id);
    }

    /**
     * 新增，插入所有字段
     *
     * @param illegalData 新增的记录
     * @return 返回影响行数
     */
    public int insert(IllegalData illegalData) {
        return illegalDataMapper.insert(illegalData);
    }

    /**
     * 新增，忽略null字段
     *
     * @param illegalData 新增的记录
     * @return 返回影响行数
     */
    public int insertIgnoreNull(IllegalData illegalData) {
        return illegalDataMapper.insertIgnoreNull(illegalData);
    }

    public IllegalData findIllegalDataEnd(String type, String battalion) {
        return illegalDataMapper.selectOne(Wrappers.<IllegalData>lambdaQuery()
                .eq(IllegalData::getType, type)
                .eq(IllegalData::getBattalion, battalion)
                .orderByDesc(IllegalData::getWfsj).last("limit 1"));
    }


    public List<IllegalDept> findAll() {
        return illegalDeptMapper.selectList(null);
    }

    /**
     * 修改，修改所有字段
     *
     * @param illegalData 修改的记录
     * @return 返回影响行数
     */
    public int update(IllegalData illegalData) {
        return illegalDataMapper.update(illegalData);
    }

    /**
     * 修改，忽略null字段
     *
     * @param illegalData 修改的记录
     * @return 返回影响行数
     */
    public int updateIgnoreNull(IllegalData illegalData) {
        return illegalDataMapper.updateIgnoreNull(illegalData);
    }

    /**
     * 删除记录
     *
     * @param illegalData 待删除的记录
     * @return 返回影响行数
     */
    public int delete(IllegalData illegalData) {
        return illegalDataMapper.delete(illegalData);
    }


    public Map findIllegalDataByCode(Integer id, String startDate, String endDate, Integer sectionId) {
        //默认取一周
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            startDate = DataTime.getStartDate();
            endDate = DataTime.getEndDate();
        }
        String dui = null;
        if (sectionId != null) {
            Section section = sectionMapper.selectByPrimaryKey(sectionId);
            String sectionName = section.getSectionName();
            dui = sectionName.substring(0, sectionName.indexOf("队") + 1);
        }

        String staffnum = null;
        if (id != null) {
            Staff staff = staffMapper.selectByPrimaryKey(id);
            staffnum = staff.getStaffNum();
        }

        Map<String, Object> map = new HashMap<>();
        //执法总量
        Integer illegalSum = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                .eq(StringUtils.isNotEmpty(staffnum), IllegalData::getWarningSignal, staffnum)
                .between(IllegalData::getWfsj, startDate, endDate)
                .like(StringUtils.isNotEmpty(dui), IllegalData::getBattalion, dui));
        //重点执法
        int illegalDataEmphasis = illegalDataMapper.findIllegalDataEmphasis(staffnum, startDate, endDate, dui);
        map.put("illegalSum", illegalSum);
        map.put("illegalEmphasis", illegalDataEmphasis);
        map.put("illegalRest", illegalSum - illegalDataEmphasis);
        return map;
    }

    public List<Map> findIllegalline(Integer id, String startTime, String endTime) throws ParseException {
        Staff staff = staffMapper.selectByPrimaryKey(id);
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            startTime = DataTime.getStartDate();
            endTime = DataTime.getEndDate();
        }

        List startEnd = com.zygh.lz.util.DateUtil.getStartEnd(startTime, endTime);
        String[] time = new String[startEnd.size()];
        int[] problem = new int[startEnd.size()];
        for (int i = 0; i < startEnd.size(); i++) {
            //执法总数
            int illegalCount = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                    .eq(IllegalData::getWarningSignal, staff.getStaffNum())
                    .between(IllegalData::getWfsj, DateUtil.beginOfDay(cn.hutool.core.date.DateUtil.parse(startEnd.get(i).toString())).toString(),
                            DateUtil.endOfDay(cn.hutool.core.date.DateUtil.parse(startEnd.get(i).toString())).toString()));
            time[i] = startEnd.get(i).toString();
            problem[i] = illegalCount;
        }
        List<Map> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("time", time);
        map.put("problem", problem);
        list.add(map);
        return list;
    }

    public Map findIllegalData(Integer id, String startTime, String endTime, Integer sectionId) {
        //默认取一周的数据
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            startTime = DataTime.getStartDate();
            endTime = DataTime.getEndDate();
        }
        //Map illegalDataByCode = findIllegalDataByCode(id, startTime, endTimd, sectionId);
        String dui = null;
        if (sectionId != null) {
            Section section = sectionMapper.selectByPrimaryKey(sectionId);
            String sectionName = section.getSectionName();
            dui = sectionName.substring(0, sectionName.indexOf("队") + 1);
        }
        String staffnum = null;
        if (id != null) {
            Staff staff = staffMapper.selectByPrimaryKey(id);
            staffnum = staff.getStaffNum();
        }
        Map<String, Object> maps = new HashMap<>();
        List<Illegals> list = new ArrayList<>();
        //执法总量
        Integer illegalSum = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                .eq(StringUtils.isNotEmpty(staffnum), IllegalData::getWarningSignal, staffnum)
                .between(IllegalData::getWfsj, startTime, endTime)
                .like(StringUtils.isNotEmpty(dui), IllegalData::getBattalion, dui));
        //重点执法
        int illegalDataEmphasis = illegalDataMapper.findIllegalDataEmphasis(staffnum, startTime, endTime, dui);
        Illegals illegals = new Illegals();
        illegals.setName("重点执法").setValue(illegalDataEmphasis);
        list.add(illegals);
        Illegals illegal5 = new Illegals();
        illegal5.setName("其他执法").setValue(illegalSum - illegalDataEmphasis);
        list.add(illegal5);
        maps.put("large", list);

        //分类
        List<Illegal> illegals1 = illegalMapper.selectList(Wrappers.<Illegal>lambdaQuery()
                .ne(Illegal::getType, "其他")
                .groupBy(Illegal::getType));
        List<Illegals> lists = new ArrayList<>();
        for (Illegal illegal2 : illegals1) {
            //获取违法代码
            List<Illegal> illegalwf = illegalMapper.selectList(Wrappers.<Illegal>lambdaQuery()
                    .eq(Illegal::getType, illegal2.getType()));
            List<String> list1 = new ArrayList<>();
            for (Illegal illegales : illegalwf) {
                list1.add(illegales.getIllegalCode());
            }
            list1.add(illegal2.getIllegalCode());
            Integer wfcount = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                    .like(StringUtils.isNotEmpty(dui), IllegalData::getBattalion, dui)
                    .in(IllegalData::getWfxw, list1)
                    .eq(IllegalData::getWarningSignal, staffnum)
                    .between(IllegalData::getWfsj, startTime, endTime));
            Illegals illegals2 = new Illegals();
            illegals2.setName(illegal2.getType()).setValue(wfcount);
            lists.add(illegals2);

        }
        Illegals illegals3 = new Illegals();
        illegals3.setName("其他执法").setValue(illegalSum - illegalDataEmphasis);
        lists.add(illegals3);
        maps.put("subclasses", lists);

        Staff staff = staffMapper.selectByPrimaryKey(id);
        //个人排名
        List<Map<String, Object>> illegalDateRanking = illegalDataMapper.findIllegalDateRanking(staff.getStaffNum(), startTime, endTime);
        //前六名
        List<Map<String, Object>> illegalDateRankings = illegalDataMapper.findIllegalDateTop3(startTime, endTime);
        List<Map<String, Object>> merge = DistanceUtil.merge(illegalDateRanking, illegalDateRankings);
        Map<String, Object> map = new HashMap<>();
        map.put("illegalData", maps);
        map.put("ranking", merge);
        return map;
    }


    public PageInfo<IllegalData> findIllegalDataByInfo(int id, String startDate, String endDate, String type, Integer current, Integer size) {

        Staff staff = staffMapper.selectByPrimaryKey(id);
        if (staff == null) {
            return null;
        }
        String code = staff.getStaffNum();
        if (StringUtils.isEmpty(code)) {
            return null;
        }
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            startDate = DataTime.getStartDate();
            endDate = DataTime.getEndDate();
        }

        //获取不同类型的违法代码
        List<Illegal> illegals1 = illegalMapper.selectList(Wrappers.<Illegal>lambdaQuery()
                .eq(StringUtils.isNotBlank(type), Illegal::getType, type));
        List<String> list = new ArrayList<>();
        for (Illegal illegal : illegals1) {
            list.add(illegal.getIllegalCode());
        }
        PageHelper.startPage(current, size);
        //获取警员违法数
        List<IllegalData> wfcount = illegalDataMapper.selectList(Wrappers.<IllegalData>lambdaQuery()
                .eq(IllegalData::getWarningSignal, code)
                .in(IllegalData::getWfxw, list)
                .between(IllegalData::getCondition, startDate, endDate)
                .orderByDesc(IllegalData::getCondition));
        PageInfo<IllegalData> pageInfo = new PageInfo<>(wfcount);
        return pageInfo;
    }


    public Map dataStatistics(Integer id) {
        Map<String, Object> map = new HashMap<>();
        //根据部门名称模糊查询
        Section section = sectionMapper.selectByPrimaryKey(id);
        String sectionTel = null;
        String sectionName = null;
        if (section != null && id != null) {
            boolean flse = true;
            int i = 0;
            do {
                i++;
                if (i > 6 || section.getSectionPid() == 74) {
                    flse = false;
                } else {
                    section = sectionMapper.selectByPrimaryKey(section.getSectionPid());
                }
            } while (flse);
            if (section.getSectionPid() == 74 && !section.getSectionName().contains("支队")) {
                sectionTel = null;
            } else {
                sectionTel = section.getSectionTel();
            }
            sectionName = section.getSectionName().substring(0, section.getSectionName().indexOf("队") + 1);
            sectionName = sectionName.replace("支", "大");
        }
        Date date = new Date();
        DateTime startDate = DateUtil.beginOfDay(date);
        DateTime endDate = DateUtil.endOfDay(date);
        //违法数据
//        Integer illegalData = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
//                .like(StringUtils.isNotEmpty(sectionName), IllegalData::getBattalion, sectionName)
//                .between(IllegalData::getWfsj, startDate, endDate));
        //调度数据
//        Integer dispatch = informationUserMapper.dispatch(id, startDate.toString(), endDate.toString());


        //警情，当前接处警
        Integer policeData = policeDataMapper.selectCount(Wrappers.<PoliceData>lambdaQuery()
                .eq(StringUtils.isNotEmpty(sectionTel), PoliceData::getCzhdw, sectionTel)
                .between(PoliceData::getJjsj01, startDate, endDate));
        map.put("particulars", policeData);
        if (policeData == 0) {
            Integer count = policeDataMapper.selectCount(Wrappers.<PoliceData>lambdaQuery()
                    .eq(StringUtils.isNotEmpty(sectionTel), PoliceData::getCzhdw, sectionTel)
                    .between(PoliceData::getJjsj01, DataTime.getStartDay(), endDate));
            map.put("particulars", count);
        }

        //事故
        Integer accident = policeDataMapper.accident(sectionTel, startDate.toString(), endDate.toString(), "事故");
//        map.put("illegal", illegalData);
//        map.put("dispatch", dispatch);
        map.put("accident", accident);


        //警情总量

        //事故警情
        //现场执法

        Integer xc = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                .like(StringUtils.isNotEmpty(sectionName), IllegalData::getBattalion, sectionName)
                .between(IllegalData::getWfsj, startDate, endDate)
                .eq(IllegalData::getType, 1));

        map.put("sceneNum", xc);
        if (xc == 0) {
            Integer num = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                    .like(StringUtils.isNotEmpty(sectionName), IllegalData::getBattalion, sectionName)
                    .between(IllegalData::getWfsj, DataTime.getStartDay(), endDate)
                    .eq(IllegalData::getType, 1));
            map.put("sceneNum", num);
        }

        //非现场执法
        Integer fxc = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                .like(StringUtils.isNotEmpty(sectionName), IllegalData::getBattalion, sectionName)
                .between(IllegalData::getWfsj, startDate, endDate)
                .eq(IllegalData::getType, 2));
        map.put("offSceneNum", fxc);
        if (fxc == 0) {
            Integer fnum = illegalDataMapper.selectCount(Wrappers.<IllegalData>lambdaQuery()
                    .like(StringUtils.isNotEmpty(sectionName), IllegalData::getBattalion, sectionName)
                    .between(IllegalData::getWfsj, DataTime.getStartDay(), endDate)
                    .eq(IllegalData::getType, 2));
            map.put("offSceneNum", fnum);
        }
        return map;
    }


}